package com.uduemc.jcms.common.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

public class PageDataUtil {

	@Data
	@AllArgsConstructor
	public static class PageData<T> {
		Collection<T> rows;
		long total;
	}

	// 返回 easyui.datagrid 可识别的数据格式
	public static <T> PageData<T> easyuiResult(Collection<T> infos) {
		return easyuiResult(infos, infos.size());// new PageData<T>(infos, infos.size());
	}

	// 返回 easyui.datagrid 可识别的数据格式
	public static <T> PageData<T> easyuiResult(Page<T> infos) {
		return new PageData<T>(infos.getRecords(), infos.getTotal());
	}

	// 返回 easyui.datagrid 可识别的数据格式
	public static <T> PageData<T> easyuiResult(Collection<T> infos, long total, String... fields) {
		if (CollUtil.isNotEmpty(infos) && ArrayUtil.isNotEmpty(fields)) {
			infos.forEach(item -> {
				for (String field : fields) {
					List<Field> declaredFields = fieldList(item.getClass());
					for (Field declaredField : declaredFields) {
						if (declaredField.getName().equals(field)) {
							declaredField.setAccessible(true);
							try {
								declaredField.set(item, null);
							} catch (IllegalArgumentException e) {
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							}
							break;
						}
					}
				}
			});
		}
		return new PageData<T>(infos, total);
	}

	// 返回 easyui.datagrid 可识别的数据格式, 同时利用反射，将参数2传入过来的字段进行赋予null值
	public static <T> PageData<T> easyuiResult(Page<T> infos, String... fields) {
		List<T> records = infos.getRecords();
		if (CollUtil.isNotEmpty(records) && ArrayUtil.isNotEmpty(fields)) {
			records.forEach(item -> {
				for (String field : fields) {
					List<Field> declaredFields = fieldList(item.getClass());
					for (Field declaredField : declaredFields) {
						if (declaredField.getName().equals(field)) {
							declaredField.setAccessible(true);
							try {
								declaredField.set(item, null);
							} catch (IllegalArgumentException e) {
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							}
							break;
						}
					}
				}
			});
		}
		return new PageData<T>(records, infos.getTotal());
	}

	public static List<Field> fieldList(Class<? extends Object> class1) {
		List<Field> fieldList = new ArrayList<>();
		Class<?> tempClass = class1;
		while (tempClass != null) {// 当父类为null的时候说明到达了最上层的父类(Object类).
			fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
			tempClass = tempClass.getSuperclass(); // 得到父类,然后赋给自己
		}
		return fieldList;
	}
}
